package com.shunan.miaosha.config;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.shunan.miaosha.beans.Users;
import com.shunan.miaosha.redis.RedisService;
import com.shunan.miaosha.redis.UserKeyPrefix;

@Component
public class UserArgumentHandlerMethodArgumentResolver extends HandlerMethodArgumentResolverComposite {

	@Autowired
	private RedisService redisService;
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return Users.class==parameter.getParameterType();
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		
		HttpServletResponse response=webRequest.getNativeResponse(HttpServletResponse.class);
		HttpServletRequest request=webRequest.getNativeRequest(HttpServletRequest.class);
		
		String cookieToken=getCookieToken(request);
		String paramToken=request.getParameter("token");
		String token=StringUtils.isEmpty(cookieToken)?paramToken:cookieToken;
		if(token==null){
			return null;
		}else{
			Users user=redisService.get(UserKeyPrefix.user, token, Users.class);
			/*
			 * 还需要将cookie重新发给浏览器，重新设置token到redis
			 * 以便于刷新过期时间
			 */
			addCookie(response,token,user);
			return user;
		}
		
	}
	
	private String getCookieToken(HttpServletRequest request){
		Cookie[]cookies= request.getCookies();
		for(Cookie c:cookies){
			if(c.getName().equals("token")){
				return c.getValue();
			}
		}
		return null;		
	}
	
	private void addCookie(HttpServletResponse response,String token,Users user){
		redisService.set(UserKeyPrefix.user,"token",user);
		Cookie cookie=new Cookie("token",token);
		cookie.setPath("/");
		cookie.setMaxAge(UserKeyPrefix.user.expireSeconds());
		response.addCookie(cookie);
	}
}
